<template>
  <div class="search-container">
    <!-- 顶部搜索栏 -->
    <!-- Tips: 在 van-search 外层增加 form 标签，且 action 不为空，即可在 iOS 输入法中显示搜索按钮。 -->
    <!-- 简单的说frorm是为了让移动端书法有搜索按钮 -->
    <form
      class="search-form"
      action="/"
    >
      <van-search
        v-model="searchText"
        show-action
        placeholder="请输入搜索关键词"
        @focus="onFocus"
        @search="onSearch"
        @cancel="onCancel"
        background="#3296fa"
      />
    </form>
    <SearchResult
      :searchText="searchText"
      v-if="isResultShow"
    ></SearchResult>
    <SearchSuggest
      @updateSearch="updateSearchFn"
      :searchText="searchText"
      v-else-if="searchText"
    ></SearchSuggest>
    <SearchHistory
      @allDelete="allDeleteFn"
      @selectDelete="selectDeleteFn"
      :searchHistory="searchHistory"
      v-else
    ></SearchHistory>
  </div>
</template>

<script>
import SearchHistory from './components/search_history.vue'
import SearchSuggest from './components/search_suggest.vue'
import SearchResult from './components/search_result.vue'
import { getItem, setItem } from '@/utils/storage'
export default {
  name: 'SearchIndex',
  components: {
    SearchHistory,
    SearchSuggest,
    SearchResult
  },
  props: {},
  data () {
    return {
      searchText: '',
      isResultShow: false,
      searchHistory: getItem('TOUTIAO_SEARCH_HISTORIES') || []
    }
  },
  // 计算属性
  computed: {},
  // 侦听器
  watch: {
    searchHistory (value) {
      setItem('TOUTIAO_SEARCH_HISTORIES', value)
    }
  },
  created () { },
  mounted () { },
  methods: {
    onSearch (val) {
      const index = this.searchHistory.indexOf(val)
      if (index !== -1) {
        this.searchHistory.splice(index, 1)
      }
      this.searchHistory.unshift(val)
      this.isResultShow = true
    },
    onCancel () {
      this.$router.back()
    },
    onFocus () {
      this.isResultShow = false
    },
    updateSearchFn (search, bool) {
      this.isResultShow = bool
      this.searchText = search
    },
    allDeleteFn () {
      this.searchHistory = []
    },
    selectDeleteFn (index) {
      this.searchHistory.splice(index, 1)
    }
  }
}
</script>

<style scoped lang="less">
.search-container {
  padding-top: 110px;
  .van-search__action {
    color: white;
  }
  .search-form {
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    z-index: 1;
  }
}
</style>
